package vip.liux.front.infrastructure.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import vip.liux.front.infrastructure.tenant.TenantFilter;

import java.util.List;

import static vip.liux.web.config.WebAutoConfiguration.createFilterBean;

@Configuration
@EnableWebMvc
public class MvcConfiguration implements WebMvcConfigurer {

    private final ObjectMapper objectMapper;

    public MvcConfiguration(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
        localeInterceptor.setParamName("lang");
        registry.addInterceptor(localeInterceptor).addPathPatterns("/**");
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {

        converters.stream().filter(MappingJackson2HttpMessageConverter.class::isInstance).findFirst()
                .ifPresent(converter -> {
                    MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
                    jacksonConverter.setObjectMapper(objectMapper);
                });
    }

    @Bean
    public FilterRegistrationBean<TenantFilter> tenantFilter() {
        TenantFilter filter = new TenantFilter();
        return createFilterBean(filter, -2147483646);
    }
}
